package monitor

import (
	"net/http"
	"strconv"
	"time"

	"main/handlers"

	"github.com/gin-gonic/gin"
)

// Response 结构体表示整个响应
type ProjectHealthCalendarResponse struct {
	DATE    Resource `json:"date"`
	Warning Resource `json:"warning"`
	Unknown Resource `json:"unknown"`
	Health  Resource `json:"health"`
}

type HealthData struct {
	Warning int `json:"warning"`
	Unknown int `json:"unknown"`
	Health  int `json:"health"`
}

// ProjectHealthCalendar 处理获取告警数据的请求
func ProjectHealthCalendar(c *gin.Context) {
	projectIDStr := c.Query("project_id")
	projectID, err := strconv.Atoi(projectIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid project ID"})
		return
	}

	// 构建 SQL 查询
	query := `  
		SELECT b.alarm_config_name, b.alarm_correct_value, a.*  
		FROM alarm_event a  
		LEFT JOIN alarm_config b ON a.alarm_config_id = b.alarm_config_id  
		LEFT JOIN hosts c ON c.host_id = b.host_id
		WHERE c.project_id = ?  
		AND a.alarm_event_mask != 1  
		AND DATE_FORMAT(a.alarm_event_time, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m')  
	`
	// 执行查询
	results, err := handlers.ExecuteQuery(query, projectID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Error executing query", "details": err.Error()})
		return
	}

	// 创建一个 map 来存储每天的统计数据
	dataMap := make(map[string]*HealthData)

	for _, row := range results {
		// 假设 row 中有一个时间字段，名为 `alarm_event_time`，并且是一个时间戳
		eventTime, ok := row["alarm_event_time"].(time.Time)
		if !ok {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid event time format"})
			return
		}
		dateKey := eventTime.Format("2006-01-02") // 格式化为 YYYY-MM-DD

		// 初始化 HealthData 结构体
		if _, exists := dataMap[dateKey]; !exists {
			dataMap[dateKey] = &HealthData{
				Warning: 0,
				Unknown: 0,
				Health:  0,
			}
		}

		execStatus, _ := row["alarm_event_exec_status"].(int64)

		// 根据 exec_status 更新相应的计数
		if execStatus != 1 {
			dataMap[dateKey].Unknown++ // 假设这里是增加 Health 的计数
		} else if row["alarm_event_alarm_status"].(int64) == 0 {
			dataMap[dateKey].Health++
		} else {
			dataMap[dateKey].Warning++
		}
	}

	// 将字典转换为数组
	var result []map[string]interface{}
	for date, counts := range dataMap {
		result = append(result, map[string]interface{}{
			"date":    date,
			"warning": counts.Warning,
			"unknown": counts.Unknown,
			"health":  counts.Health,
			"total":   counts.Warning + counts.Unknown + counts.Health,
		})
	}

	c.JSON(http.StatusOK, result) // 返回转换后的响应
}
